package com.crrc.sandameter.view

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import com.cj.mvvmlib.base.activity.BaseVmActivity
import com.cj.mvvmlib.base.viewmodel.BaseViewModel
import com.cj.mvvmlib.util.ToastUtil
import com.crrc.sandameter.DeviceManager
import com.crrc.sandameter.databinding.ActivityCalibrationBinding
import com.crrc.sandameter.device.COMUtil
import com.crrc.sandameter.device.REGISTER_ADD
import java.util.Random
import kotlin.math.abs

class CalibrationActivity : BaseVmActivity<BaseViewModel>() {
    private var weightResult = 0.0

    companion object {
        const val TAG = "CalibrationActivity"
    }

    private val currentInterval = 50L // 打点间隔时间
    private lateinit var calibrationBinding: ActivityCalibrationBinding
    override fun useTitleBar(): Boolean {
        return false
    }

    override fun layoutId(): View {
        calibrationBinding = ActivityCalibrationBinding.inflate(layoutInflater)
        return calibrationBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        handler.postDelayed(tickRunnable, currentInterval)
    }

    override fun initData() {
    }

    override fun setListener() {
        calibrationBinding.calibration1Bt.setOnClickListener {
            val content = calibrationBinding.value1Et.text.toString()
            if (content.isEmpty()) {
                ToastUtil.showShortToast("请输入校准重量")
            } else {
                val value = content.toInt() * 10
                DeviceManager.calibrateDevice(value, 1)
                Handler(Looper.getMainLooper()).postDelayed({
                    DeviceManager.setScale(0)
                }, 1000)
            }
            it.isEnabled = false
        }
        calibrationBinding.calibration2Bt.setOnClickListener {
            val content = calibrationBinding.value2Et.text.toString()
            if (content.isEmpty()) {
                ToastUtil.showShortToast("请输入校准重量")
            } else {
                val value = content.toInt() * 10
                DeviceManager.calibrateDevice(value, 2)
            }
            it.isEnabled = false
        }
        calibrationBinding.calibration3Bt.setOnClickListener {
            val content = calibrationBinding.value3Et.text.toString()
            if (content.isEmpty()) {
                ToastUtil.showShortToast("请输入校准重量")
            } else {
                val value = content.toInt() * 10
                DeviceManager.calibrateDevice(value, 3)
            }
            it.isEnabled = false
        }
        calibrationBinding.backBt.setOnClickListener {
            finish()
        }
        calibrationBinding.getWeightBt.setOnClickListener {
            DeviceManager.getWeight()
        }
        calibrationBinding.zeroBt.setOnClickListener {
            DeviceManager.zeroDevice(1)
            calibrationBinding.calibration1Bt.isEnabled = true
            calibrationBinding.calibration2Bt.isEnabled = true
            calibrationBinding.calibration3Bt.isEnabled = true
            calibrationBinding.lockBt.isEnabled = true
            calibrationBinding.trackBt.isEnabled = true
            calibrationBinding.setRangeBt.isEnabled = true
        }
        calibrationBinding.lockBt.setOnClickListener {
            DeviceManager.setLock(true)
            it.isEnabled = false
        }
        calibrationBinding.trackBt.setOnClickListener {
            DeviceManager.setTrack(true)
            it.isEnabled = false
        }
        calibrationBinding.setRangeBt.setOnClickListener {
            val range = calibrationBinding.rangeEt.text.toString()
            if (range.isEmpty()) {
                ToastUtil.showShortToast("请输入范围值")
            } else {
                val value = range.toInt()
                DeviceManager.setRange(value)
            }
            it.isEnabled = false
        }
    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        DeviceManager.deviceData.observe(this) {
            val functionCode = it.substring(0, 4)
            if (functionCode == REGISTER_ADD.ZERO_VALUE) {
                Log.d(TAG, "清零成功返回数据：$it")
            }
            if (functionCode == REGISTER_ADD.POINT1_VALUE || functionCode == REGISTER_ADD.POINT2_VALUE || functionCode == REGISTER_ADD.POINT3_VALUE) {
                ToastUtil.showShortToast("校准成功")
                Log.d(TAG, "校准成功返回数据：$it")
            }
            if (functionCode == REGISTER_ADD.WEIGHT_VALUE) {
                Log.d(TAG, "获取重量返回数据：$it")
                val weightData = it.substring(10, 18)
                Log.d(TAG, "获取到的重量数据：$weightData")
                val weight = divideByTen(COMUtil.decodeHEX(weightData))
                val value = abs(weightResult - weight)
                if (value > 0.5) {
                    weightResult = weight
                    val weightStr = when {
                        weight < 5 && weight > 0 -> {
                            "0"
                        }
                        weight > -5 && weight < 0 -> {
                            "0"
                        }
                        else -> {
                            "${correctNumber(weight)}.${getRandomNumber()}"
                        }
                    }
                    calibrationBinding.currentWeightTv.text = "${weightStr}g"
                }
            }
        }
    }

    // 使用主线程的 Handler
    private val handler = Handler(Looper.getMainLooper())

    // 打点任务的 Runnable
    private val tickRunnable = object : Runnable {
        override fun run() {
            DeviceManager.getWeight()
            handler.postDelayed(this, currentInterval)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(tickRunnable)
    }

    private fun divideByTen(number: Long): Double {
        val result = number.toDouble() / 10.0
        return String.format("%.1f", result).toDouble()
    }

    private fun formatDeviceId(deviceId: String?): String? {
        if (deviceId == null || deviceId.length < 12) {
            return null
        }

        val builder = StringBuilder() // 截取前12个字符
        val truncatedId = deviceId.substring(0, 12)

        for (i in truncatedId.indices) {
            builder.append(truncatedId[i])
            if (i % 2 == 1 && i < 11) { // 每隔两个字符添加一个下划线
                builder.append("-")
            }
        }
        return builder.toString().uppercase() // 转换为大写
    }

    /**
     * 获取1-5的随机数
     */
    private fun getRandomNumber(): Int {
        val random = Random()
        return random.nextInt(5) + 1
    }

    /**
     * 修正数字
     */
    private fun correctNumber(number: Double): Int { // 定义需要比较的整数列表
        val targets = listOf(1000, 2000, 3000, 4000, 5000, 6000)

        // 遍历目标整数
        for (target in targets) { // 计算当前数字与目标整数之间的差值
            val difference = abs(number - target)

            // 判断差值是否小于或等于 5
            if (difference <= 5) { // 如果是，返回目标整数
                return target
            }
        }

        // 如果没有找到匹配项，返回原始数字
        return number.toInt()
    }
}